package org.niu.tree;

import java.util.Arrays;

public class ReconstructTree {
    public TreeNode reConstructBinaryTree(int [] pre,int [] vin) {
        return buildTree(pre,vin);
    }
    TreeNode buildTree(int[] pre, int[] vin){
        if(pre.length == 0 || vin.length == 0){
            return null;
        }
        int i;
        TreeNode root = new TreeNode(pre[0]);
        for(i = 0;i <= pre.length;i++){
            if(vin[i] == pre[0]){
                int[] pre_l = Arrays.copyOfRange(pre,1,i+1);
                int[] pre_r = Arrays.copyOfRange(pre,i+1,pre.length);
                int[] in_l = Arrays.copyOfRange(vin,0,i);
                int[] in_r = Arrays.copyOfRange(vin,i+1,vin.length);
                root.left = buildTree(pre_l,in_l);
                root.right = buildTree(pre_r,in_r);
            }
        }

        return root;
    }
}
